package cn.jsj.hzu.qm.facecloud.ciuser.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.jasper.tagplugins.jstl.core.If;

import com.alibaba.fastjson.JSON;

import cn.edu.hzu.jsj.utils.BeanFactory;
import cn.jsj.hzu.qm.facecloud.ciuser.pojo.Cilab;
import cn.jsj.hzu.qm.facecloud.ciuser.pojo.Ciuser;
import cn.jsj.hzu.qm.facecloud.ciuser.service.CiuserService;
import cn.jsj.hzu.qm.facecloud.utils.Page;

/**
 * Servlet implementation class CiuserServlet
 */
public class CiuserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 参数mode
	 * 
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;encoding=UTF-8");;

		PrintWriter out = response.getWriter();

		CiuserService ciuserService = BeanFactory.getBean("ciuserService");

		String modeString = request.getParameter("mode");
		if (modeString == null) {
			response.getWriter().write("no mode");
			response.sendError(566);
			return;
		}

		int mode;
		mode = Integer.parseInt(modeString);

		switch (mode) {
		// 增加
		case 11: {
			// V1.1更新：将禁止通过此接口注册！
			// 如需注册，须取得管理员激活码
			
			// V1.1 Delete
			// V2.3 重新恢复了下面的代码
			
			String sid = request.getParameter("sid");
			String name = request.getParameter("name");
			String password = request.getParameter("password");
			String email = request.getParameter("email");
			String memo = request.getParameter("memo");

			
			 

			
			Ciuser ciuser = (Ciuser)request.getSession().getAttribute("ciuser");
			
			
			
			//新用户在注册
//			if(ciuser == null || ciuser.getType() != 1 || ) {
//				response.sendError(511, "无接口权限");
//			
//				return;
////				out.write("{'state':" + r + "}");
////				if (r == 1) {
////					ciuser = ciuserService.findCiuserBySid(sid);
////					request.setAttribute("ciuser", ciuser);
////					request.getRequestDispatcher("checkin/regSuccess.jsp").forward(request, response);
////				}
////				return;
//			}
			
			//管理员在新增用户
			// 管理员！
			// 只有系统管理员才有权限直接跳过激活码新增账号
			if (ciuser != null && (ciuser.getType() == 1)) {
				int r = ciuserService.addCiuser(sid, name, password, email, memo);
				Ciuser aCiuser = ciuserService.findCiuserBySid(sid);
				
				//通过人
				aCiuser.setPass_by(ciuser.getName());
				
				ciuserService.modifyCiuser(aCiuser);
				
				out.write("{'state':'admin-register'}");
				return;
			}
			else{
				response.sendError(511, "无接口权限");
				
				return;
			}
			
			
//			 V1.1 end Delete
			
			
//			return;
			
		}
		
		// 按【激活码】新增用户
		case 12:{
			/*
			
			'mode':'12',
			'activation_code':$("#activation_code").val(),
			'sid':$("#sid").val(),
			'name':$("#name").val(),
			'password':$("#newPwd").val(),
			'email':$("#email").val()
			
			*/
			String sid = request.getParameter("sid");
			String name = request.getParameter("name");
			String password = request.getParameter("password");
			String email = request.getParameter("email");
			String activation_code = request.getParameter("activation_code");
			
			if(sid == "" || sid == null) {
				response.sendError(512, "禁止空的用户名");
				return;
			}
			
			// 检查激活码
			
			Ciuser code_ciuser = ciuserService.findCiuserByAactivation_code(activation_code);
			
			// 当前日期
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String now_date = df.format(new Date());
			if (code_ciuser == null || code_ciuser.getNumber_of_times() <= 0 || now_date.compareTo(code_ciuser.getActivation_code_end()) > 0) {
				
				response.sendError(512, "激活码无效");
				return;
			}
			
			
			
			
			
			// end 检查激活码
			
			
			int r = ciuserService.addCiuser(sid, name, password, email, "-");
			if (r != 1) {
				response.sendError(512, "插入失败");
				return;
			}
			
			Ciuser ciuser = ciuserService.findCiuserBySid(sid);
			
			// 通过人
			ciuser.setPass_by(code_ciuser.getName());
			
			ciuserService.modifyCiuser(ciuser);
			
			//次数减一
			code_ciuser.setNumber_of_times(code_ciuser.getNumber_of_times() - 1);
			
			ciuserService.modifyCiuser(code_ciuser);
			
			
			return;
		}
		
		// 没有删除的操作

		// 修改
		//31 : 表单方式提交，将会返回一个新页面，新页面中利用js跳转
		case 31: {
			System.out.println(31);
			
			String idString = request.getParameter("id");
			String sid = request.getParameter("sid");
			String name = request.getParameter("name");
			String password = request.getParameter("password");
			String email = request.getParameter("email");
			String memo = request.getParameter("memo");

			if (idString == null || sid == null || name == null || password == null || email == null || memo == null) {
				out.write("{'state':'param lost'}");
				return;
			}
			int id = Integer.parseInt(idString);
			Ciuser ciuser = ciuserService.findCiuserById(id);
			
			String typeString = request.getParameter("type");
			
			String is_availableString = request.getParameter("is_available");
			
			if (typeString != null) {
				int type = Integer.parseInt(typeString);
				ciuser.setType(type);
			}
			if (is_availableString != null) {
				int is_available = Integer.parseInt(is_availableString);
				ciuser.setIs_available(is_available);
			}
			
			if(ciuser == null) {
				out.write("{'state':'id not found'}");
				return;
			}
			
			ciuser.setName(name);
			ciuser.setPassword(password);
			ciuser.setEmail(email);
			ciuser.setMemo(memo);
			
			int i = ciuserService.modifyCiuser(ciuser);
//			out.write("{'state':"+i+"}");
			ciuser = ciuserService.findCiuserById(id);
			
			Ciuser sessionCiuser = 
					(Ciuser) request.getSession().getAttribute("ciuser");
			
			//我修改我自己
			if(ciuser.getSid().equals(sessionCiuser.getSid())) {
				request.getSession().setAttribute("ciuser", ciuser);
			}
			//否则，是不用更新Session的
			
			
			//jumpToServlet是为了安插请求域做的
			out.write("<script>alert('更新成功'); window.location.href='checkin/jumpToServlet?mode=ciuser&id="+id+"'</script>");
			return;
		}
		
		// 激活码部分
		case 32:{
			
			//用户id
			String idString = request.getParameter("id");
			
			// 新激活码
			String activation_code = request.getParameter("activation_code");
			
			//剩余激活次数
			String number_of_timesString = request.getParameter("number_of_times");
			
			//截止日期
			String activation_code_end = request.getParameter("activation_code_end");
			
			int id = Integer.parseInt(idString);
			Ciuser ciuser = ciuserService.findCiuserById(id);
			
			//剩余次数
			int number_of_times = Integer.parseInt(number_of_timesString);
			
			ciuser.setActivation_code(activation_code);
			ciuser.setNumber_of_times(number_of_times);
			ciuser.setActivation_code_end(activation_code_end);
			
			ciuserService.modifyCiuser(ciuser);
			
			Ciuser sessionCiuser = 
					(Ciuser) request.getSession().getAttribute("ciuser");
			//我修改我自己
			if(ciuser.getSid().equals(sessionCiuser.getSid())) {
				request.getSession().setAttribute("ciuser", ciuser);
			}
			//否则，是不用更新Session的.
			
			// 更新session的目的：
			// 使得更新个人信息完成后能够立即看到更改后的效果，
			// 因为个人信息页是用jsp的el表达式写的。
			
			/*
			 * 给未来的读者：
			 * 这段代码读起来是难了点，鄙陋的语法，清奇的思路，让人摸不着头脑。
			 * 不过我为你加油，你总能够看懂的！
			 * */

			// 实在不行，推倒重做吧！d=====(￣▽￣*)b 
			/*
			 
				 /'　\\　　 //\\ 
				　　　\\　 //　`\ 
				　　　 \\ //           祝你：
				　　　.-'^'-. 
				　　.' a___a `.           春节愉快 阖家欢乐！
				　 ==　(___)　== 
				　　'. ._I_. .'           心想事成 永无BUG ！
				____/.`-----'.\____ 
				   [###(__)####             
				   
			 * */
			return;
		}
		
		// 登录
		// 按照sid和密码查询学生
		case 41: {
			request.getSession().invalidate();
			String sidString = request.getParameter("sid");
			String passwordString = request.getParameter("password");

			if (sidString == null || passwordString == null) {
				out.write("{'state':'error'}");
				return;
			}
			System.out.println(sidString);
			System.out.println(passwordString);
			Ciuser ciuser = ciuserService.findCiuserBySid(sidString);
			
			//没有查询到用户名或密码错误
			if (ciuser == null || ciuser.getPassword().equals(passwordString) == false) {
				out.write("{'state':'error'}");
				return;
			} else {
				if(ciuser.getIs_available() == 1) {
					out.write("{'state':'success', 'type':'"+ciuser.getType()+"'}");

					request.getSession().setAttribute("ciuser", ciuser);
					return;
				}
				else {
					out.write("{'state':'refused'}");

					return;
				}
				
			}
			// break;
		}

		// 查询sid是否存在
		case 42: {
			String sidString = request.getParameter("sid");
			
			if (sidString == null) {
				out.write("{'state':'error'}");
				return;
			}

			if (ciuserService.isCiuserExisted(sidString) == true) {
				out.write("{'state':'existed'}");
				return;
			}else {
				out.write("{'state':'notfound'}");
				return;
			}
			
		}
		
		//查询所有用户
		//!不在建议使用
		case 43:{
			
			List<Ciuser> ciusers = ciuserService.getAllCiusers(); //所有的用户
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append('[');
			for(Ciuser myCiuser : ciusers ) {
				
				myCiuser.setPassword("*");//此处抹去密码，不发送到前端
				
				stringBuilder.append(myCiuser.toJsonString());
				stringBuilder.append(',');
			}
			stringBuilder.append(']');
			
			out.write(stringBuilder.toString());
			// System.out.println(stringBuilder.toString());
			return;
		}
		
		// 查询用户是否具有实验室二级管理员权限
		case 44:{
			//TODO
			return;
		}
		
		// 按type分页查询用户
		case 45:{
			String typeString = request.getParameter("type");
			
			int type = Integer.parseInt(typeString);
			
			String pageString = request.getParameter("page");
			String perpageString = request.getParameter("perpage");
			
			int sum; 
			int page = Integer.parseInt(pageString);
			int perpage = Integer.parseInt(perpageString);
			
			try {
				//Page:初始化 关于分页查询的有关内容
				List<Ciuser> ciusers;
				if (type != -1) {
					sum = ciuserService.getUsersSumByType(type);
					ciusers = ciuserService.getUsersByType(type, new Page(page, perpage, sum));
				}
				else {
					sum = ciuserService.getNotAvailableUsersSumByType();
					ciusers = ciuserService.getNotAvailableUsersByPage(new Page(page, perpage, sum));
				}
				
				// FastJson
				String ciuserString = JSON.toJSONString(ciusers);
				out.write(ciuserString);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				System.out.println("page-err");
				out.write("[]");
			}
			return;
//			StringBuilder stringBuilder = new StringBuilder();
//			stringBuilder.append('[');
//			for(Ciuser myCiuser : ciusers ) {
//				
//				myCiuser.setPassword("*");//此处抹去密码，不发送到前端
//				
//				stringBuilder.append(myCiuser.toJsonString());
//				stringBuilder.append(',');
//			}
//			stringBuilder.append(']');
//			
//			out.write(stringBuilder.toString());
			// System.out.println(stringBuilder.toString());
//			return;
		}
		
		//某类用户总数
		case 46:{
			
			String typeString = request.getParameter("type");
			if (typeString == null) {
				response.sendError(546,"typeString error");
			}
			int type = Integer.parseInt(typeString);
			
			int user_sum;
			if (type != -1) {
				user_sum = ciuserService.getUsersSumByType(type);
			}
			else {
				user_sum = ciuserService.getNotAvailableUsersSumByType();
			}
			
			
			out.write(""+user_sum);
			return;
		}

		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
